//封装购物车模块
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./userStore";
import { findNewCartListAPI,insertCartAPI,delCartAPI } from "@/apis/cart";

export const useCartStore=defineStore('cart',()=>{
    const userStore=useUserStore()
    const isLogin=computed(()=>userStore.userInfo.token)
    //1.定义state -cartList
    const cartList=ref([])
    //2.定义action-addCart
    const addCart=async (goods)=>{
        const {skuId,count}=goods
        if(isLogin.value){
            await insertCartAPI({skuId,count})
            updateNewList()
        }else{
            //添加购物车操作
            //已添加过 count+1
            //没添加过 push
            //通过匹配传过来的商品对象的skuID能不能再cartList中找到
            const item=cartList.value.find((item)=> goods.skuId===item.skuId)
            if(item){
                item.count++
            }else{
                cartList.value.push(goods)
            }
        }
    }

    const delCart=async(skuId)=>{
        if(isLogin.value){
            await delCartAPI([skuId])
            updateNewList()
        }else{
            //删：1.找到要删除项的下标值splice 2.数组过滤filter
            const idx=cartList.value.findIndex((item)=>skuId===item.skuId)
            cartList.value.splice(idx,1)
        }
    }

    //获取最新购物车列表action
    const updateNewList=async()=>{
        const res=await findNewCartListAPI()
        cartList.value=res.result
    }

    //单选
    const singleCheck=(skuId,selected)=>{
        const item=cartList.value.find((item)=>item.skuId===skuId)
        item.selected=selected
    }
    //清除
    const clearCart=()=>{
        cartList.value=[]
    }

    //计算
    const allCount=computed(()=>cartList.value.reduce((a,c)=>a+c.count,0))
    const allPrice=computed(()=>cartList.value.reduce((a,c)=>a+c.price*c.count,0))

    const isAll=computed(()=>cartList.value.every((item)=>item.selected))
    const allCheck=(selected)=>{
        cartList.value.forEach(item=>item.selected=selected)
    }
    const selectedCount=computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count,0))
    const selectedPrice=computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count*c.price,0))
    return {
        cartList,
        addCart,
        delCart,
        allCount,allPrice,
        singleCheck,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,clearCart,updateNewList
    }
},{
    persist:true
})
